package com.auxgroup.smarthome.enterprise.service;

import com.auxgroup.smarthome.enterpriseapi.EnterpriseApi;
import com.auxgroup.smarthome.enterpriseapi.requestbody.SearchUserDetailsBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.DeviceUserInfo;
import com.auxgroup.smarthome.enterpriseapi.responsebody.UserDetails;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by kevinchen on 2017/3/12.
 */
@Service
public class DeviceUserReportService {

    @Autowired
    private ProductService productService;
    @Autowired
    private DeviceManageService deviceManageService;


    /**
     * 查询用户,最近发现竟然可以查询全部用户
     * @param pk
     * @param body
     * @return
     */
    public ApiResponse<UserDetails> searchUser(String pk, SearchUserDetailsBody body){
        UserDetails resultResponse = EnterpriseApi.UserManagement.searchUser(productService.getToken(pk), pk, body);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 获取所有用户(去重 唯一的uid)
     * @param pk
     * @return
     */
    public List<DeviceUserInfo> getAllDeviceUserList(String pk){
        Set<DeviceUserInfo>  allUsers = new HashSet<DeviceUserInfo>();
        Set<String> allDeviceDids = deviceManageService.getAllDeviceDids(pk);
        if (allDeviceDids==null){
            return null;
        }
        for(Iterator<String> iterator = allDeviceDids.iterator();iterator.hasNext();){
            String did = iterator.next();
            List<DeviceUserInfo> userList = getUserListOnDevice(pk, did);
            if (userList != null){
                allUsers.addAll(userList);
            }
        }
        return new ArrayList<DeviceUserInfo>(allUsers);
    }


    /**
     * 通过设备did 获取绑定该设备的用户
     * @param pk
     * @param did
     * @return
     */
    public List<DeviceUserInfo> getUserListOnDevice(String pk,String did){
        ApiResponse<UserDetails> userDetails = searchUser(pk, new SearchUserDetailsBody("did", did));
        if (userDetails.getData() != null ){
            return userDetails.getData().getObjects();
        }
        return null;
    }



}
